package ReefStats::Controller::Users;

use strict;
use warnings;
use base 'Catalyst::Controller::FormBuilder';
use String::Random qw(random_string);
use DateTime;
use URI;
use Crypt::CBC;

sub do_reset_password : Local Form {
    my ( $self, $c, $reset_token, $encrypted_email_address ) = @_;

    if ( $self->formbuilder->submitted && $self->formbuilder->validate ) {

	$c->log->info('processing form');

	$reset_token = $self->formbuilder->params('reset_token');

        my $email_address = Crypt::CBC->new(
            -key    => 'app key',
            -cipher => 'DES',
        )->decrypt($encrypted_email_address);

        $c->log->info("email address [$email_address]");

	my $new_password = $self->formbuilder->params('new_password');
	$c->log->info("new password [$new_password]");

	my $new_password_repeated = $self->formbuilder->params('new_password_repeated');
	$c->log->info("new password again [$new_password_repeated]");

	if( $new_password ne $new_password_repeated ) {
		$c->log->info('passwords did not match');
		$c->stash->{message} = 'Passwords did not match';
		return;
	}

        my $user =
          $c->model('ReefStatsDB::Users')
          ->search( { email_address => $email_address } );

	if( $user ) {
		$user = $user->first();
		$user->password($new_password);
		$user->update();
        	$c->response->redirect( $c->uri_for('/login') );
		return;
	}

	$c->stash->{message} = 'Unknown error occured when resetting password.  Please try again.';
	
    }
    elsif ( defined $reset_token && defined $encrypted_email_address ) {
        $c->log->info(
            "fielding password reset [$reset_token] [$encrypted_email_address]"
        );

        my $email_address = Crypt::CBC->new(
            -key    => 'app key',
            -cipher => 'DES',
        )->decrypt($encrypted_email_address);
        $c->log->info("email address [$email_address]");

	$self->formbuilder->params( name => 'reset_token', type => 'hidden', value => $reset_token );
	$self->formbuilder->params( name => 'encrypted_email_address', type => 'hidden', value => $encrypted_email_address );

        my $user =
          $c->model('ReefStatsDB::Users')
          ->search( { email_address => $email_address } );

        if ($user) {
            $user = $user->first;

            if ( $user->password_reset_token eq $reset_token ) {
                $c->log->info('reset tokens match');
                if( DateTime->now()->delta_ms($user->password_reset_request_timestamp)->minutes > 60*24) {
                    $c->log->info('more than 24 hours have passed since request');
                }
            }
            else {
                $c->log->info('reset tokens did not match');
            }
        }
	else {
		$c->stash->message('Encountered an unknown problem when trying to lookup email address.  Please request another password reset');
        	$c->response->redirect( $c->uri_for('request_reset_password') );
	}
    }
    else {
        $c->response->redirect( $c->uri_for('request_reset_password') );
    }
}

sub request_reset_password : Local Form {
    my ( $self, $c ) = @_;

    if ( $self->formbuilder->submitted && $self->formbuilder->validate ) {
        my $user =
          $c->model('ReefStatsDB::Users')
          ->search(
            { email_address => $self->formbuilder->field('email_address') } );

        if ($user = $user->first()) {
            $c->log->info(
                'sending password reset email to ' . $user->email_address() );
            my $reset_token = random_string( '.' x 10 );
            $c->log->info("password reset token set to $reset_token");
            $user->password_reset_token($reset_token);
            $user->password_reset_request_timestamp( DateTime->now() );
            $user->update();

            my $cipher = Crypt::CBC->new(
                -key    => 'app key',
                -cipher => 'DES',
                -salt   => 1,
            );
            my $encrypted_email_address =
              $cipher->encrypt( $user->email_address );

            my $uri = URI->new( $c->uri_for('do_reset_password') );
            $uri->path_segments( $uri->path_segments(), $reset_token,
                $encrypted_email_address );
            $c->flash->{html_message} = 'Typically this would be sent in an email to verify the user, but since we are just testing now, simply <a href="' . $uri->canonical . '">click here</a> to reset your password.';
        	$c->response->redirect( $c->uri_for('/login') );
        }
		
	$c->stash->{message} = 'The user cannot be found';
    }
}

1;

__END__

=head1 NAME

ReefStats::Controller::Users - Catalyst Controller

=head1 DESCRIPTION

Catalyst Controller.

=head1 METHODS

=cut

=head2 index 

=cut

=head1 AUTHOR

Joshua McAdams

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

